package com.qiwx.pigeon.data.network;

import android.app.Activity;
import android.text.TextUtils;

import com.google.gson.Gson;
import com.qiwx.pigeon.BuildConfig;
import com.qiwx.pigeon.Utils.NumberUtil;
import com.qiwx.pigeon.Utils.SSlUtiles;
import com.qiwx.pigeon.app.AppManager;
import com.qiwx.pigeon.helper.LogHelper;


import org.json.JSONObject;

import java.io.IOException;
import java.util.HashMap;
import java.util.Map;
import java.util.concurrent.TimeUnit;

import okhttp3.FormBody;
import okhttp3.Interceptor;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.RequestBody;
import okhttp3.Response;
import okhttp3.ResponseBody;

public class CustomerOkHttpClient {

    public static OkHttpClient client;
    private static final int DEFAULT_TIMEOUT = 30 * 1000;

    private CustomerOkHttpClient() {
        throw new UnsupportedOperationException("cannot be instantiated");
    }

    private static void create() {
        OkHttpClient.Builder builder = new OkHttpClient.Builder()
                .addNetworkInterceptor(new CacheInterceptor())
//                .addInterceptor( new LoggingInterceptor())
                .addInterceptor(new ParamsInterceptor())
                .retryOnConnectionFailure(true)
                .connectTimeout(DEFAULT_TIMEOUT, TimeUnit.MILLISECONDS)
                .writeTimeout(DEFAULT_TIMEOUT, TimeUnit.MILLISECONDS)
                .readTimeout(DEFAULT_TIMEOUT, TimeUnit.MILLISECONDS);
        //如果是沙盒环境或debug环境就添加
//        if(BuildConfig.OkhttpEventDuration){
//            builder.eventListenerFactory(HttpEventListener.FACTORY);
//        }
        //如果允许打印日志则添加日志信息
        if (BuildConfig.DEBUG) {
            builder.addInterceptor(new LoggingInterceptor());
        }
        client = builder.build();
    }

    public static OkHttpClient getClient() {
        if (client == null) {
            create();
        }
        return client;
    }

    /**
     * Fresco 加载图片专用 为了支持Https要要对Fresco配置OkHttpClient
     *
     * @return
     */
    public static OkHttpClient getFrescoOkHttpClient() {
        OkHttpClient.Builder builder = new OkHttpClient.Builder()
                .retryOnConnectionFailure(true)
                .connectTimeout(DEFAULT_TIMEOUT, TimeUnit.SECONDS)
                .writeTimeout(DEFAULT_TIMEOUT, TimeUnit.SECONDS)
                .readTimeout(DEFAULT_TIMEOUT, TimeUnit.SECONDS);
        builder.hostnameVerifier(new SSlUtiles.TrustAllHostnameVerifier());
        builder.sslSocketFactory(SSlUtiles.createSSLSocketFactory());
        return builder.build();
    }

    static class CacheInterceptor implements Interceptor {
        @Override
        public Response intercept(Chain chain) throws IOException {
            Request request = chain.request();
            Response response = chain.proceed(request);

            String cacheControl = request.cacheControl().toString();
            if (TextUtils.isEmpty(cacheControl)) {
                cacheControl = "public, max-age=60 ,max-stale=2419200";
            }
            return response.newBuilder()
                    .header("Cache-Control", cacheControl)
                    .removeHeader("Pragma")
                    .build();
        }
    }

    ;

    static class ParamsInterceptor implements Interceptor {
        @Override
        public Response intercept(Chain chain) throws IOException {
            Request request = chain.request();
            Request.Builder builder1 = request.newBuilder();
            int userId = 0;
//            if(user!=null){
//                userId = user.getUserId();
//            }
            if (request.method().toUpperCase().equals("POST")) {
                builder1.url(request.url().url() + "?userId=" + (userId == 0 ? "" : String.valueOf(userId)));
                builder1.addHeader("X-Requested-With", "XMLHttpRequest");
                builder1.tag(builder1.tag(null).build());
            } else {
                builder1.addHeader("X-Requested-With", "XMLHttpRequest");
            }
            builder1.addHeader("X-Requested-With", "XMLHttpRequest");
            Request request1 = builder1.build();
            return chain.proceed(request1);
        }

    }


    static class LoggingInterceptor implements Interceptor {
        private static final String TAG = "OkHttpManger";

        @Override
        public Response intercept(Chain chain) throws IOException {
            Request request = chain.request(); //request还有其他方法没有用
            RequestBody body = request.body();//release 版 必须取消日志
            // StringBuffer sb = new StringBuffer();
            Map<String, String> map = new HashMap<>();

            if (body instanceof FormBody) {
                FormBody formBody = (FormBody) body;
                int size = formBody.size();
                if (size > 0) {
                    for (int i = 0; i < size; i++) {
                        String name = formBody.name(i);
                        String value = formBody.value(i);
                        map.put(name, value);
                    }
//                    LogUtil.e(TAG, String.format("请求参数:\n %s", sb.toString()));
                }
            }
            long t1 = System.nanoTime();
            Response response = chain.proceed(request);
            long t2 = System.nanoTime();
            String responseString = new String(response.body().bytes());
            if (!TextUtils.isEmpty(responseString)) {
                //服务器相应时间
                String responseTime = NumberUtil.showDouble((t2 - t1) / 1e6d);
                //LogHelper logHelper=new LogHelper();
                //logHelper.setRequestUrl(request.url().toString());

                String requestJson = "";
                try {
                    requestJson = new Gson().toJson(map);
                } catch (Exception e) {
                    e.printStackTrace();
                }
                JSONObject jsonObject = new JSONObject();
                String extraInfo = "";
                try {
                    jsonObject.put("requestUrl", request.url().toString());
                    jsonObject.put("responseTime", responseTime);
                    extraInfo = jsonObject.toString();
                } catch (Exception e) {
                    e.printStackTrace();
                }

                Activity activity = AppManager.getAppManager().currentActivity();
                String currentActivity = "activity";
                if (activity != null) {
                    currentActivity = activity.getClass().getSimpleName();
                }
                LogHelper.printJson(TAG, extraInfo, "requestUrl + responseTime");
                LogHelper.printJson(TAG, requestJson, "Request ( currentActivity = " + currentActivity + " )");
                LogHelper.printJson(TAG, responseString, "response");

//                LogUtil.e(TAG, String.format("响应行: %s", response.toString())
//                        + ",contentLength:"+response.body().contentLength()
//                        + "\n"
//                        + (String.format("Access Server in %.1fms ,返回值: %s", (t2 - t1) / 1e6d, response.body().contentLength()<=1024*1024?responseString:"")));//小于1M的response内容才在log中输出
            } else {
                responseString = "null";
            }
            return response.newBuilder().body(ResponseBody.create(response.body().contentType(), responseString)).build();
        }
    }


}
